import { View, Input } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useRef, useState } from 'react'
import utils from '@/utils'
import BtLayout from '@/BtComponents/BtLayout'
import BtForm from '@/BtComponents/BtForm'
import BtFormItem from '@/BtComponents/BtFormItem'
import BtPicker from '@/BtComponents/BtPicker'
import { Button } from "@taroify/core"
import { formContextProvider } from '@/BtComponents/BtForm/formContextProvider'
import './index.scss'

export default function FormDemo () {

  const fromRef = useRef<any>(null)

  const [ form, setForm ] = useState({
    name: '1',
    password: '',
    country: ''
  })

  const [ selector ] = useState([{id: '1', name: 'China'}, {id: '2', name: 'USA'}])

  const rules = {
    name: [
      { required: true, message: '用户名不能为空' },
    ],
    password: [
      { required: true, message: '密码不能为空' },
      { min: 6, max: 20, message: '密码长度必须在 6 到 20 个字符之间' }
    ]
  };

  useLoad(async () => {
    await utils.$initPage()
  })

  const onChange = (value, attr: string) => {
    const item = {}
    item[attr] = value
    setForm({
      ...form,
      ...item
    })
  }

  const onSubmit = async () => {
    const errs =  await fromRef.current.validate()
    if (!errs) {
      utils.$toast('提交成功')
      return
    }
  }

  return (
    <BtLayout config={{title: '表单'}}>
      <View className='form-demo'>
        <formContextProvider.Provider>
          <BtForm ref={fromRef} model={form} rules={rules}>
            <BtFormItem label='姓名' prop='name'>
              <Input value={form.name} placeholder='姓名' onInput={(e) => onChange(e.detail.value, 'name')}></Input>
            </BtFormItem>
            <BtFormItem label='密码' prop='password'>
              <Input password value={form.password} placeholder='密码' onInput={(e) => onChange(e.detail.value, 'password')}></Input>
            </BtFormItem>
            <BtFormItem label='国籍' prop='country'>
              <BtPicker value={form.country} onChange={e => onChange(e.detail.value, 'country')} selector={selector}></BtPicker>
            </BtFormItem>
            <Button className='btn' color='primary' size='medium' onClick={onSubmit}>提交</Button>
          </BtForm>
        </formContextProvider.Provider>
      </View>
    </BtLayout>
  )
}
